<template>
    <div id="racipes-list">
        <div class="rl-top">
            <el-button class="refurbish" type="primary" @click="refurbish">刷新</el-button>
            <div class="ri-right">
                <button class="btn-act" @click="addBgOpen">添加</button>
                <button :class="delBtnsClass" @click="delBgs" :disabled="delBtnsControl">删除</button>
            </div>
        </div>
        <el-alert
          title="点击封面图可在图片查看窗口进行更换"
          type="info"
          close-text="知道了">
        </el-alert>
        <div class="rl-content">
            <el-table ref="multipleTable"
                 v-loading="loading"
                element-loading-background="rgba(0, 0, 0, 0.4)"
                :data="tableData"
                tooltip-effect="dark"
                style="width: 100%"
                :header-row-class-name="tableRowHeaderClassName"
                :row-class-name="tableRowClassName"
                type=index
                @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55"></el-table-column>
                <el-table-column type="index" :index="indexMethod" label="序号" width="50"></el-table-column>
                <el-table-column prop="name" label="封面图" >
                  <template slot-scope="scope">
                    <img  @click="viewImg(scope.row)" :src="scope.row.backgroundSrc?scope.row.backgroundSrc:'../../../assets/img/errorImg.png'" :onerror="errorImage" alt="">
                  </template>
                </el-table-column>
                <el-table-column label="菜单状态">
                  <template slot-scope="scope">
                    <span :class="scope.row.state==1? 'state-ok':'state-ing'">
                      {{scope.row.state==1? '当前展示':'未展示'}}
                    </span>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="200px">
                  <template slot-scope="scope">
                    <button class="control-btn change" @click="openChange(scope.row)">修改</button>
                    <button class="control-btn delete" @click="delBg(scope.row.backgroundId)">删除</button>
                  </template>
                </el-table-column>
            </el-table>
            <div class="pageControl">
               <el-pagination
                background
                @current-change="handleCurrentChange"
                :current-page="current_page"
                :page-size="10"
                layout="prev, pager, next"
                :total="total">
              </el-pagination>
            </div>
        </div>
        <!-- 修改图片状态 -->
         <el-dialog title="食谱审核" :visible.sync="dialogFormVisible">
          <div class="changeWin">
            <div class="cW-row">
              <span>食谱图片：</span>
              <img :src="winShowData.backgroundSrc" alt="">
            </div>
            <div class="cW-row">
              <span>当前状态：</span>
              <b> {{winShowData.state==1? '当前背景':'未展示'}} </b>
            </div>
            <div class="cW-row">
              <span>操作：</span>
              <div class="pw-box">
                  <input type="radio" value="1" v-model="changeState" id="okInput" name="state">
                  <span></span>
              </div>
              <label for="okInput">当前背景</label>
              <div class="pw-box">
                  <input type="radio" value="0" v-model="changeState" id="noInput" name="state">
                  <span></span>
              </div>
              <label for="noInput">未展示</label>
            </div>
          </div>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取 消</el-button>
            <el-button type="primary" @click="changeStateFun()">确 定</el-button>
          </div>
        </el-dialog>
        <!-- 添加背景图片 -->
         <el-dialog title="添加背景图" :visible.sync="dialogFormVisibleAdd">
          <div class="addWin">
            <div class="menu-img">
                <input type="file" accept="image/*" @change="showImg()" ref="img">
                <div class="img-wrap" v-if="imgUpload.imgShow">
                    <img :src="imgUpload.imgSrc" alt="">
                    <i class="el-icon-refresh menu-refresh" @click="changeImg()"></i>
                </div>
                <div v-if="imgUpload.uploading">正在上传</div>
                <div class="mi-tips">
                    添加首页背景图
                    <p>（建议尺寸1920*500，支持上传图片格式有jpg、jpeg、png、gif、webp）</p>
                </div>
            </div>
          </div>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisibleAdd = false">取 消</el-button>
            <el-button type="primary" @click="addBg()">确 定</el-button>
          </div>
        </el-dialog>
        <!-- 预览并更换背景图片 -->
         <el-dialog title="图片查看" :visible.sync="dialogFormVisibleImg">
          <img class="bigImg" :src="bigImg?bigImg:'../../../assets/img/errorImg.png'" :onerror="errorImage" alt="">
          <div slot="footer" class="dialog-footer">
            <el-button type="success" @click="imgChangeBgFun()">
              <input class="imgChangeBg" type="file" accept="image/*" @change="showBgChange()" ref="imgChangeBg">
              更 换</el-button>
            <el-button @click="dialogFormVisibleImg = false">取 消</el-button>
            <el-button type="primary" @click="changeBgFun()">提 交</el-button>
          </div>
        </el-dialog>
    </div>
</template>
<script>
export default {
  data () {
    return {
      tableData: [],
      multipleSelection: [],
      total: 0,
      current_page: 1,
      stateList: [['state-ok', '000'], ['state-ing', '111'], ['state-no', '222']],
      loading: true,
      errorImage: 'this.src="' + require('../../../assets/img/errorImg.png') + '"',
      dialogFormVisible: false,
      winShowData: '',
      changeState: 0,
      delBtnsControl: true,
      delBtnsClass: '',
      bigImg: '',
      dialogFormVisibleImg: false,
      dialogFormVisibleAdd: false,
      imgUpload: {
        imgShow: false,
        imgSrc: null
      },
      backgroundId: ''
    }
  },

  methods: {
    // 更换背景图
    imgChangeBgFun () {
      this.$refs.imgChangeBg.dispatchEvent(new MouseEvent('click'))
    },
    showBgChange () {
      var that = this
      if ((this.$refs.imgChangeBg.files[0].size / 1024 / 1024) > 5) {
        this.$message({
          message: '文件大小不得超过5M,请重新上传',
          type: 'warning'
        })
        this.$refs.imgChangeBg.value = ''
      } else {
        var f = new FileReader()
        f.readAsDataURL(this.$refs.imgChangeBg.files[0])
        f.onload = function () {
          that.bigImg = f.result
        }
      }
    },
    changeBgFun () {
      console.log()
      if (this.$refs.imgChangeBg.value === '') {
        this.$message({
          message: '请选择图片',
          type: 'info'
        })
      } else {
        const loading = this.$loading({
          lock: true,
          text: '背景上传中...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.6)'
        })
        const file = this.$refs.imgChangeBg.files[0]
        const param = new FormData()
        param.append('backgroundId', this.backgroundId)
        param.append('backgroundSrc', file)
        const config = {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        }
        this.$axios.put('Menu/Admin/updateBackGround', param, config)
          .then(res => {
            console.log(res.data)
            loading.close()
            if (res.data.code === 200) {
              this.$message({
                message: res.data.message,
                type: 'success'
              })
              this.dialogFormVisibleImg = false
              this.getData()
              this.$refs.imgChangeBg.value = ''
            } else {
              this.$message({
                message: res.data.message,
                type: 'info'
              })
            }
          })
          .catch(err => {
            console.log(err)
          })
      }
      // const loading = this.$loading({
      //   lock: true,
      //   text: '背景上传中...',
      //   spinner: 'el-icon-loading',
      //   background: 'rgba(0, 0, 0, 0.6)'
      // })
      // const file = this.$refs.img.files[0]
      // const param = new FormData()
      // param.append('backgroundSrc', file)
      // const config = {
      //   headers: {
      //     'Content-Type': 'multipart/form-data'
      //   }
      // }
      // this.$axios.post('Menu/Admin/addBackground', param, config)
      //   .then(res => {
      //     console.log(res.data)
      //     loading.close()
      //     if (res.data.code === 200) {
      //       this.$message({
      //         message: res.data.message,
      //         type: 'success'
      //       })
      //       this.dialogFormVisibleAdd = false
      //       this.getData()
      //       this.$set(this.imgUpload, 'imgSrc', null)
      //       this.$set(this.imgUpload, 'imgShow', false)
      //     } else {
      //       this.$message({
      //         message: res.data.message,
      //         type: 'info'
      //       })
      //     }
      //   })
      //   .catch(err => {
      //     console.log(err)
      //   })
    },
    // 添加背景图
    addBgOpen () {
      this.dialogFormVisibleAdd = true
      this.$set(this.imgUpload, 'imgSrc', null)
      this.$set(this.imgUpload, 'imgShow', false)
    },
    showImg () {
      var that = this
      if ((this.$refs.img.files[0].size / 1024 / 1024) > 5) {
        this.$message({
          message: '文件大小不得超过5M,请重新上传',
          type: 'warning'
        })
        this.$refs.img.value = ''
      } else {
        var f = new FileReader()
        f.readAsDataURL(this.$refs.img.files[0])
        f.onload = function () {
          that.imgUpload.imgSrc = f.result
        }
        that.imgUpload.imgShow = true
      }
    },
    changeImg () {
      this.$refs.img.dispatchEvent(new MouseEvent('click'))
    },
    addBg () {
      const loading = this.$loading({
        lock: true,
        text: '背景上传中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.6)'
      })
      const file = this.$refs.img.files[0]
      const param = new FormData()
      param.append('backgroundSrc', file)
      const config = {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      }
      this.$axios.post('Menu/Admin/addBackground', param, config)
        .then(res => {
          console.log(res.data)
          loading.close()
          if (res.data.code === 200) {
            this.$message({
              message: res.data.message,
              type: 'success'
            })
            this.dialogFormVisibleAdd = false
            this.getData()
            this.$set(this.imgUpload, 'imgSrc', null)
            this.$set(this.imgUpload, 'imgShow', false)
          } else {
            this.$message({
              message: res.data.message,
              type: 'info'
            })
          }
        })
        .catch(err => {
          console.log(err)
        })
    },
    // 图片预览
    viewImg (key) {
      this.bigImg = key.backgroundSrc
      this.backgroundId = key.backgroundId
      this.dialogFormVisibleImg = true
    },
    closeImg () {
      this.dialogFormVisibleImg = false
    },
    refurbish () {
      this.$router.go(0)
    },
    indexMethod (index) {
      return ((index + 1) + 10 * (this.current_page - 1))
    },
    toggleSelection (rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row)
        })
      } else {
        this.$refs.multipleTable.clearSelection()
      }
    },
    handleSelectionChange (val) {
      this.multipleSelection = val
      if (val.length === 0) {
        this.delBtnsControl = true
        this.delBtnsClass = ''
      } else {
        this.delBtnsControl = false
        this.delBtnsClass = 'btn-act'
      }
      console.log(this.multipleSelection)
    },
    handleCurrentChange (val) {
      this.current_page = val
      this.getData()
    },
    getData () {
      this.$axios({
        method: 'get',
        url: '/Menu/Admin/findAll',
        params: {
          pageNow: this.current_page,
          pageSize: 10
        }
      }).then(data => {
        console.log(data.data)
        if (data.data.code === 200) {
          console.log(data.data.object.list[0])
          this.loading = false
          this.tableData = data.data.object.list
          this.total = data.data.object.total
          this.current_page = data.data.object.prePage + 1
        }
      }).catch(error => {
        console.log(error)
      })
    },
    tableRowClassName () {
      return 'row-class'
    },
    tableRowHeaderClassName () {
      return 'header-row-class-name'
    },
    delBg (backgroundId) {
      console.log(backgroundId)
      this.$confirm('此操作将永久删除该食谱, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$axios({
          method: 'delete',
          url: '/Menu/Admin/deleteBackground',
          params: {
            backgroundId
          }
        }).then(data => {
          console.log(data)
          if (data.data.code === 200) {
            this.$message({
              message: '删除成功',
              type: 'success'
            })
            this.getData()
          }
        }).catch(error => {
          console.log(error)
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    delBgs () {
      this.$confirm('此操作将永久删除选中的菜单, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        var arr = []
        for (const key of this.multipleSelection) {
          arr.push(key.backgroundId)
        }
        arr = arr.toString()
        console.log(arr)
        this.$axios({
          method: 'delete',
          url: '/Menu/Admin/batchDeleteBackground',
          params: {
            backgroundId: arr
          }
        }).then(data => {
          console.log(data)
          if (data.data.code === 200) {
            this.$message({
              message: '删除成功',
              type: 'success'
            })
            this.getData()
          }
        }).catch(error => {
          console.log(error)
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    openChange (key) {
      console.log(key)
      this.winShowData = key
      this.dialogFormVisible = true
      this.changeState = key.state
    },
    changeStateFun () {
      if (this.changeState === this.winShowData.state) {
        this.dialogFormVisible = false
        // this.$message.error('窗口关闭，本次未修改')
      } else {
        this.$axios({
          method: 'post',
          url: '/Menu/Admin/updateBackgroundToOne',
          params: {
            backgroundId: this.winShowData.backgroundId
          }
        }).then(data => {
          console.log(data.data)
          if (data.data.code === 200) {
            this.$message({
              message: '修改成功',
              type: 'success'
            })
            this.getData()
            this.dialogFormVisible = false
          }
        }).catch(error => {
          console.log(error)
        })
      }
    }
  },
  mounted () {
    this.getData()
  }
}
</script>

<style lang="less" scoped>
.bigImg{
  width: 600px;
  display: block;
  margin: 0 auto;
  height:auto;
  max-height: 500px;
}
#racipes-list{
    width: 98%;
    margin: 0 auto;
}
.rl-top{
    height: 50px;width: 100%;
    line-height:50px;
    margin-top: 20px;
    .ri-right{
        float: right;
        width: 200px;
        display:grid;
        height: 50px;line-height: 50px;
        grid-template-columns: repeat(2, 90px);
        place-content: space-around space-between;
        button{
            border-radius: 5px;
            height: 30px;line-height: 30px;
            text-align: center;
            background-color: #BFBFBF;
            color: #fff;
            &:hover{
                cursor: pointer;
            }
        }
        .btn-act{
            background-color: #FF9512;
        }
    }
}
.rl-content{
    .has-gutter tr{
        background-color: #E8E7E7 !important;
    }
    .control-btn{
        width: 80px;
        height: 30px;line-height: 30px;
        text-align: center;
        border-radius:5px;
        margin: 0 5px;
        color: #fff;
    }
    .change{
        background-color: #FF9512;
    }
    .delete{
        background-color: #C4C4C4;
    }
    .state-no .el-table_1_column_6>cell{color: #FFBD6c !important;}
    .cell{color: #FFBD6c !important}
    .state-ok{color: #2FC25B;}
    .state-ps{color: #FF4329;}
    .pageControl{
      li{
        &:hover{
          color: #FF4329 !important
        }
      }
    }
    .pageControl{
      text-align: right;
      margin: 20px 0;
    }
    .state-ing{color:#FFC176}
    .state-no{color:red}
}
.changeWin{
  width: 60%;
  margin: 0 auto;
  img{
    width: 200px;
    height: auto;
    object-fit: cover
  }
  div{
    margin: 0 0 20px 0;
    span{
      display: inline-block;
      width: 100px;
      text-align: right;
    }
  }
  .pw-box{
    margin: 0;
    display: inline-block;
    width: 15px; height: 15px;
    // margin: 0 5px 0 0;
    position: relative;
    background-color: #fff;
    vertical-align:middle;
    border-radius: 100%;
    border: 1px solid #E5E3DF;
    input{
        opacity: 0;
        margin: 0;
        position: absolute;top: 0;left: 0;
        width: 100%;height: 100%;
        z-index: 100;
        background-color: red;
    }
    span{
        display:block;width: 8px;height:8px;
        border-radius:100%;
        background-color: #FFB31A;
        position: absolute;
        top: 50%;left: 50%;
        margin: -4px 0 0 -4px;
        z-index: 1;
    }
    input+span{
        opacity: 0;
    }
    input:checked+span{
        opacity: 1;
    }
  }
  label{
      padding:3px 10px 0 5px ;
      display: inline-block;
      font-weight: bold;
      color: rgba(0,0,0,0.4);
  }
}
.addWin{
  width: 90%;
  margin: 0 auto;
  img{
    width: 50px;
    height: 50px;
    object-fit: cover
  }
  div{
    margin: 0 0 20px 0;
    span{
      display: inline-block;
      width: 100px;
      text-align: right;
    }
  }
  .pw-box{
    margin: 0;
    display: inline-block;
    width: 15px; height: 15px;
    // margin: 0 5px 0 0;
    position: relative;
    background-color: #fff;
    vertical-align:middle;
    border-radius: 100%;
    border: 1px solid #E5E3DF;
    input{
        opacity: 0;
        margin: 0;
        position: absolute;top: 0;left: 0;
        width: 100%;height: 100%;
        z-index: 100;
        background-color: red;
    }
    span{
        display:block;width: 8px;height:8px;
        border-radius:100%;
        background-color: #FFB31A;
        position: absolute;
        top: 50%;left: 50%;
        margin: -4px 0 0 -4px;
        z-index: 1;
    }
    input+span{
        opacity: 0;
    }
    input:checked+span{
        opacity: 1;
    }
  }
  label{
      padding:3px 10px 0 5px ;
      display: inline-block;
      font-weight: bold;
      color: rgba(0,0,0,0.4);
  }
}
// 添加背景图片
.menu-img{
  position:relative;width:100%;height:390px;
  background: #eee url("https://cp1.douguo.com/static/nweb/images/add.png") no-repeat center 140px;
  input{
      width: 100%;
      height: 100%;
      opacity: 0;
  }
  textarea{color: #000;}
  .mi-tips{
      position: absolute;
      top: 225px;
      width: 100%;
      text-align: center;
      text-align: center;color: #999;font-size: 15px;line-height: 20px;
      p{
          font-size: 13px;
      }
  }
  .img-wrap{
      width: 100%;height:100%;
      position: absolute;
      top: 0;left: 0;
      z-index: 4;
      &:hover{
          .menu-refresh{
              display: block;
          }
      }
  }
  img{
      width: 100%;
      height: 100%;
      z-index: 4;
  }
  .menu-refresh{
      position: absolute;top:10px;right:10px;
      font-size: 25px;
      font-weight: bold;
      display: none;
      z-index: 4;
  }
}
.imgChangeBg{
  width: 0px;height: 0px;
  display: block;
}

</style>
